package generics_and_collections.equals;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created with IntelliJ IDEA.
 * User: Sam
 * Date: 05/02/14
 * Time: 21:18
 * To change this template use File | Settings | File Templates.
 */
public class BinarySearchTest {

	public  BinarySearchTest() {

	}

	public void execute() {
		String[] strings = {"zero", "one", "two", "three", "four"};

		// Uses natural sort order compareTo() of alphabetical Strings
		//Arrays.sort(strings);

		for(String s : strings) {
			System.out.println(s);
		}

		//System.out.println(Arrays.binarySearch(strings, "two"));

		ReSortComparator rs = new ReSortComparator();
		Arrays.sort(strings, rs);

		System.out.println("Index: " + Arrays.binarySearch(strings, "two"));

		System.out.println("After ReSortComparator");
		for(String s : strings) {
			System.out.println(s);
		}

		// If we dont pass in our Comparator, we get incorrect result, as we used rs to sort.
		System.out.println("Index: " + Arrays.binarySearch(strings, "two", rs));
	}

	static class ReSortComparator implements Comparator<String> {

		public ReSortComparator(){}

		/**
		 * is b more than a? (true = positive, false = negative)
		 * a.compare(b) appears to obey natural sort order,
		 * whereas b.compare(a) doesn't.
		 */
		public int compare(String a, String b) {
			return a.compareTo(b);
		}

		/**
		 b.compare(a):
		 zero
		 two
		 three
		 one
		 four

		 a.compare(b):
		 four
		 one
		 three
		 two
		 zero
		 */
	}
}
